package org.androidpn.server.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.androidpn.server.dao.BaseDao;
import org.androidpn.server.service.BaseService;
import org.androidpn.server.util.Filter;
import org.androidpn.server.util.Order;
import org.androidpn.server.util.Page;
import org.androidpn.server.util.Pageable;
import org.springframework.transaction.annotation.Transactional;

/**
 * service 基本dao
 * 
 * @author 蔡琪
 * 
 * @param <T>
 * @param <ID>
 */
public class BaseServiceImpl<T, ID extends Serializable> implements BaseService<T, ID> {

	private BaseDao<T, ID> baseDao;

	public BaseDao<T, ID> getBaseDao() {
		return baseDao;
	}

	public void setBaseDao(BaseDao<T, ID> baseDao) {
		this.baseDao = baseDao;
	}

	@Transactional(readOnly = true)
	public T find(ID id) {
		return (T) baseDao.find(id);
	}

	@Transactional(readOnly = true)
	public List<T> findAll() {
		return baseDao.findList(null, null, null, null);
	}

	@Transactional(readOnly = true)
	public List<T> findList(ID... ids) {
		List<T> list = new ArrayList<T>();
		for (ID id : ids) {
			list.add(find(id));
		}
		return list;
	}

	@Transactional(readOnly = true)
	public List<T> findList(Integer count, List<Filter> filters, List<Order> orders) {

		return baseDao.findList(null, count, filters, orders);
	}

	@Transactional(readOnly = true)
	public List<T> findList(Integer first, Integer count, List<Filter> filters, List<Order> orders) {

		return baseDao.findList(first, count, filters, orders);
	}

	@Transactional(readOnly = true)
	public Page<T> findPage(Pageable pageable) {

		return baseDao.findPage(pageable);
	}

	@Transactional(readOnly = true)
	public long count() {

		return baseDao.count();
	}

	@Transactional(readOnly = true)
	public long count(Filter... filters) {

		return baseDao.count(filters);
	}

	@Transactional(readOnly = true)
	public boolean exists(ID id) {

		return baseDao.find(id) != null;
	}

	@Transactional(readOnly = true)
	public boolean exists(Filter... filters) {

		return !baseDao.findList(null, null, Arrays.asList(filters), null).isEmpty();
	}

	@Transactional
	public void save(T entity) {
		baseDao.persist(entity);
	}

	@Transactional
	public T update(T entity) {

		return (T) baseDao.merge(entity);
	}

	@Transactional
	public T update(T entity, String... ignoreProperties) {

		return null;
	}

	@Transactional
	public void delete(ID id) {
		baseDao.remove(find(id));
	}

	@Transactional
	public void delete(ID... ids) {
		for (ID id : ids) {
			delete(id);
		}
	}

	@Transactional
	public void delete(T entity) {
		baseDao.remove(entity);
	}
}
